package com.yaorange.jk.web.cargo;

import com.yaorange.jk.entity.Contract;
import com.yaorange.jk.entity.ContractProduct;
import com.yaorange.jk.service.ContractProductService;
import com.yaorange.jk.web.BaseAction;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @author coach tam
 * @date 2017/11/9
 */
@Controller("outProductAction")
@Scope("prototype")
public class OutProductAction extends BaseAction {

    //船期
    private String inputDate;

    @Autowired
    private ContractProductService contractProductService;
    /**
     * 跳转到打印页面
     * @return
     */
    public String toedit(){
        return "toedit";
    }


    /**
     * 根据船期打印出货表
     * @return
     */
    public String print2() throws IOException {

        //根据船期查询到对应的出货表数据
        List<ContractProduct> cpList = contractProductService.findListByShipTime(inputDate);

        //初始化行数,列数
        int rowNo = 0;
        int cellNo = 1;

        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet("出货表");
        //设置列宽
        sheet.setColumnWidth(rowNo++,24*256);
        sheet.setColumnWidth(rowNo++,11*256);
        sheet.setColumnWidth(rowNo++,24*256);
        sheet.setColumnWidth(rowNo++,24*256);
        sheet.setColumnWidth(rowNo++,24*256);
        sheet.setColumnWidth(rowNo++,24*256);
        sheet.setColumnWidth(rowNo++,24*256);
        //合并第一行 第2-9列
        sheet.addMergedRegion(new CellRangeAddress(0,0,1,8));//横向合并单元格

        //------------------------大标题------------------------------/
        Row row = sheet.createRow(rowNo++);
        Cell  cell = row.createCell(1);
        //2015-07-->2015年07月
        String title = inputDate.replace("-","年")+"月份出货表";
        cell.setCellValue(title);
        cell.setCellStyle(bigTitle(wb));


        //------------------------小标题------------------------------/
        row  = sheet.createRow(rowNo++);
        String[] titles = new String[]{"客户","订单号","货号","数量","工厂","工厂交期","船期","贸易条款"};
        for (String titleEach:titles)
        {
            Cell cell11 = row.createCell(cellNo++);
            cell11.setCellValue(titleEach);
            cell11.setCellStyle(title(wb));

        }
        SimpleDateFormat fmt= new SimpleDateFormat("yyyy-MM-dd");
        //------------------------数据------------------------------/
        for(ContractProduct cp :cpList)
        {
            Contract c = cp.getContract();
            //将这一列的数据封装到一个数组中，方便循环遍历
            Object[] values = new Object[]{c.getCustomName(),c.getContractNo(),cp.getProductNo(),cp.getCnumber(),cp.getFactoryName(),fmt.format(c.getDeliveryPeriod()),fmt.format(c.getShipTime()),c.getTradeTerms()};
            //重置cellNo为1
            cellNo=1;
            row = sheet.createRow(rowNo++);
            for(Object value:values)
            {
                cell = row.createCell(cellNo++);
                if(value!=null)
                {
                    cell.setCellValue(value.toString());
                }

                cell.setCellStyle(text(wb));
            }
        }

        //------------------------文件下载------------------------------/
        //response中的输出流打印数据
        HttpServletResponse response = ServletActionContext.getResponse();
        //告诉浏览器这是文件下载
        response.setContentType("application/x-download");
        //文件名(处理中文问题)
        String fileName = new String((title+".xls").getBytes("gbk"),"iso-8859-1");
        response.addHeader("Content-disposition","attachment;filename="+fileName);

        OutputStream out =  response.getOutputStream();
        wb.write(out);
        out.flush();
        return null;
    }

    /**
     * 使用模板 导出Excel 表格
     * @param
     */
    public String print() throws IOException{
        //根据船期查询到对应的出货表数据
        List<ContractProduct> cpList = contractProductService.findListByShipTime(inputDate);

        //拿到模板输入流
        String realPath = ServletActionContext.getServletContext().getRealPath("/make/xlsprint/tOUTPRODUCT.xls");
        InputStream inputStream = new FileInputStream(realPath);

        Workbook wb = new HSSFWorkbook(inputStream);
        Sheet sheet = wb.getSheetAt(0);
        //表格大标题
        String title = inputDate.replace("-", "年") + "月份出货表";
        sheet.getRow(0).getCell(1).setCellValue(title);
        //设置该sheet第一列宽度，已使表格水平居中显示
        sheet.setColumnWidth(0,(short)256*22);

        //列名模板已经提供
        SimpleDateFormat fmt= new SimpleDateFormat("yyyy-MM-dd");
        //获得模板数据列的单元格样式 ， 放到数组中
        CellStyle[] cellStyles = new CellStyle[8];
        Row temp = sheet.getRow(2);
        for (int i = 0; i < cellStyles.length; i++) {
            cellStyles[i] =temp.getCell(i+1).getCellStyle();
        }
        //从第三行开始写入数据
        int rowNo = 2;
        Row row = null;
        Cell cell = null;
        for(ContractProduct cp : cpList){
            row = sheet.createRow(rowNo++);
            Contract c = cp.getContract();
            //将这一列的数据封装到一个数组中，方便循环遍历
            Object[] values = new Object[]{c.getCustomName(),c.getContractNo(),cp.getProductNo(),cp.getCnumber(),cp.getFactoryName(),fmt.format(c.getDeliveryPeriod()),fmt.format(c.getShipTime()),c.getTradeTerms()};
            for(int j = 1;j<=cellStyles.length;j++){
                cell = row.createCell(j);
                cell.setCellStyle(cellStyles[j-1]);
                if (values[j-1]!=null){
                    cell.setCellValue(values[j-1].toString());
                }
            }
        }


        //------------------------文件下载------------------------------/
        //response中的输出流打印数据
        HttpServletResponse response = ServletActionContext.getResponse();
        //告诉浏览器这是文件下载
        response.setContentType("application/x-download");
        //文件名(处理中文问题)
        String fileName = new String((title+".xls").getBytes("gbk"),"iso-8859-1");
        response.addHeader("Content-disposition","attachment;filename="+fileName);

        OutputStream out =  response.getOutputStream();
        wb.write(out);
        out.flush();
        return NONE;
    }

    public void setInputDate(String inputDate) {
        this.inputDate = inputDate;
    }



    //大标题的样式
    public CellStyle bigTitle(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short)16);
        font.setBoldweight(Font.BOLDWEIGHT_BOLD);					//字体加粗

        style.setFont(font);

        style.setAlignment(CellStyle.ALIGN_CENTER);					//横向居中
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);		//纵向居中

        return style;
    }
    //小标题的样式
    public CellStyle title(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short)12);

        style.setFont(font);

        style.setAlignment(CellStyle.ALIGN_CENTER);					//横向居中
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);		//纵向居中

        style.setBorderTop(CellStyle.BORDER_THIN);					//上细线
        style.setBorderBottom(CellStyle.BORDER_THIN);				//下细线
        style.setBorderLeft(CellStyle.BORDER_THIN);					//左细线
        style.setBorderRight(CellStyle.BORDER_THIN);				//右细线

        return style;
    }

    //文字样式
    public CellStyle text(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short)10);

        style.setFont(font);

        style.setAlignment(CellStyle.ALIGN_LEFT);					//横向居左
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);		//纵向居中

        style.setBorderTop(CellStyle.BORDER_THIN);					//上细线
        style.setBorderBottom(CellStyle.BORDER_THIN);				//下细线
        style.setBorderLeft(CellStyle.BORDER_THIN);					//左细线
        style.setBorderRight(CellStyle.BORDER_THIN);				//右细线

        return style;
    }
}
